<template>
  <div class="draggle-demo">
    <div class="draggle-list" ref="draggableList">
      <div class="draggle-item" v-for="item in list" :key="item.id">
        <span class="drag-handle">👋</span>
        {{ item.name }}
      </div>
    </div>
  </div>
</template>
<script>
import Sortable from 'sortablejs'

export default {
  name: "DraggleDemo",
  data() {
    return {
      list: [
        { id: 1, name: "选项1" },
        { id: 2, name: "选项2" },
        { id: 3, name: "选项3" },
        { id: 4, name: "选项4" },
      ],
      sortable: null
    };
  },
  mounted() {
    this.initSortable()
  },
  beforeDestroy() {
    if (this.sortable) {
      this.sortable.destroy()
    }
  },
  methods: {
    initSortable() {
      this.sortable = Sortable.create(this.$refs.draggableList, {
        handle: '.drag-handle',
        animation: 150,
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen',
        dragClass: 'sortable-drag',
        onEnd: (evt) => {
          // 更新列表顺序
          const { oldIndex, newIndex } = evt
          const [movedItem] = this.list.splice(oldIndex, 1)
          this.list.splice(newIndex, 0, movedItem)
          console.log('排序已更新:', this.list)
        }
      })
    }
  }
};
</script>
<style scoped>
.draggle-demo {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  max-width: 400px;
  margin: 20px auto;
}

.draggle-list {
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.draggle-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin: 5px 0;
  background-color: #f8f9fa;
  border-radius: 4px;
  cursor: grab;
  transition: all 0.3s ease;
  user-select: none;
}

.draggle-item:hover {
  background-color: #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.draggle-item:active {
  cursor: grabbing;
}

.drag-handle {
  margin-right: 12px;
  color: #666;
  font-size: 18px;
  cursor: grab;
}

.drag-handle:active {
  cursor: grabbing;
}

/* Sortable.js 样式 */
.sortable-ghost {
  opacity: 0.5;
  background-color: #f0f0f0;
}

.sortable-chosen {
  background-color: #e3f2fd;
}

.sortable-drag {
  opacity: 0;
}
</style>
